﻿@{
    ViewData["Title"] = "PLC读取数据配置";
    ViewData["Mbx"] = "配置管理";
    Layout = "_Default";
}

@section css{
    <style>

        .fliter {
            width: 95%;
            height: 60px;
            align-items: center;
            display: flex;
            margin-bottom: 20px;
        }

            .fliter .search-btn {
                margin-left: 20px;
            }

            .fliter .input-text {
                width: 140px;
            }

            .fliter .label-eq-code {
                margin-left: 20px;
            }

            .fliter .input-text-eq-code {
                width: 140px;
                height: 31px;
            }

            .fliter .input-text-dbcode {
                width: 100px;
                height: 23px;
            }

        .select-box {
            width: 180px;
        }
    </style>
}

@section gray{

    <div class="fliter">
        <label class="label-eq-name">PLC名称：</label>
        <input type="text" class="input-text" value="" placeholder="" id="plcName" name="plcName">
        <label class="label-eq-code">报文处理模块对象名称：</label>
        <input type="text" class="input-text input-text-eq-code" value="" placeholder="" id="moduleName" name="moduleName">
        <label class="label-eq-code">DB编号：</label>
        <input type="text" class="input-text" value="" placeholder="" id="DBCode" name="DBCode">

        <label class="label-eq-code">设备号：</label>
        <input type="text" class="input-text" value="" placeholder="" id="equipmentCode" name="equipmentCode">

        <label class="label-eq-code">任务名称：</label>
        <span class="select-box">
            <select class="select" size="1" name="jobId" id="jobId">
                <option value="0" selected>--请选择--</option>
                @foreach (var item in Model.JobSearchs)
                {
                    <option value="@item.JobId">@item.JobName</option>
                }
            </select>
        </span>
        <label class="label-eq-code">连接IP：</label>
        <span class="select-box">
            <select class="select" size="1" name="ipSearch" id="ipSearch">
                <option value="0" selected>--请选择--</option>
                @foreach (var item in Model.PlcIpSearchs)
                {
                    <option value="@item.PlcConnectId">@item.PlcConnectIp</option>
                }
            </select>
        </span>
        <input class="btn btn-primary radius search-btn" type="button" onclick="search()" value="&nbsp;&nbsp;搜索&nbsp;&nbsp;">
    </div>
    <div>
        <span class="l">
            <a class="btn btn-primary radius" href="javascript:;" onclick="common_add('添加PLC读取DB配置','/plcreaddb/plcreaddbinfoaddoredit','700','620')">
                <i class="Hui-iconfont">&#xe600;</i> 新增
            </a>
            <a class="btn btn-primary radius" href="javascript:;" onclick="common_add('添加PLC读取DB配置','/plcreaddb/PlcReadDbInfoAddMore','700','860')">
                <i class="Hui-iconfont">&#xe600;</i> 新增DB配置
            </a>
        </span>


        <a class="btn btn-secondary radius" href="javascript:;" onclick="importDemo()" style="margin-left:150px;">
            <i class="Hui-iconfont">&#xe641;</i> 模板下载
        </a>
        <a id="b" class="btn btn-secondary radius" href="javascript:;" onclick="if(file.value=='')alert('请选择xls文件');else importFun()" style="margin-left:5px;">
            <i class="Hui-iconfont">&#xe642;</i> 导入数据
        </a>
        <input type="file" id="file" class="btn btn-secondary radius" />
    </div>
}



<table class="table table-border table-bordered table-hover table-bg table-sort">
    <thead>
    </thead>
    <tbody>
    </tbody>
</table>

@section javascript{
    <script type="text/javascript" src="~/js/xlsx.full.min.js"></script>
    <script type="text/javascript" src="~/js/xlsx.core.min.js"></script>
    <script>
        $(function () {
            initData("", "", 0, 0, 0);
        });


        function search() {
            var plcName = $("#plcName").val();
            var moduleName = $("#moduleName").val();
            var DBCode = $("#DBCode").val();
            var jobId = $("#jobId").val();
            var ipSearch = $("#ipSearch").val();
            var equipmentCode = $("#equipmentCode").val();
            initData(plcName, moduleName, DBCode, jobId, ipSearch, equipmentCode);
        }

        function initData(plcName, moduleName, DBCode, jobId, ipSearch, equipmentCode) {
            $('.table-sort').dataTable({
                bProcessing: true, //DataTables 载入数据时，是否显示‘进度’提示
                bAutoWidth: false, //自动宽度
                bSort: false, //排序功能
                paging: true, //是否分页
                bInfo: true, //页脚信息,默认为 true
                bStateSave: false, //状态保存
                sPaginationType: "full_numbers", //分页显示样式
                serverSide: true, //启用服务器分页
                //sAjaxSource: "/admin/functionlist", //服务端请求数据接口
                searching: true, //关闭 datatables 的搜索框
                destroy: true, //解决重新渲染问题
                iDisplayLength: 10, //每页显示数量
                ajax: {
                    url: "/plcreaddb/getallplcreaddbinfo",
                    type: "POST",
                    contentType: "application/x-www-form-urlencoded",
                    async: false,
                    dataType: "json",
                    data: function (data) {
                        data.plcName = plcName;
                        data.moduleName = moduleName;
                        data.DBCode = DBCode;
                        data.jobId = jobId;
                        data.ipSearch = ipSearch;
                        data.equipmentCode = equipmentCode;
                    },
                    dataFilter: function (json) {
                        console.log(json);
                        return json;
                    }
                },

                aoColumns: [
                    // mDataProp：绑定数据属性
                    // sDefaultContent：设置默认值
                    // sClass：添加 class 属性，不懂的直接去掉
                    // sTtile：设置列标题
                    // sWidth：设置列宽度
                    // sTtile 设置的内容，会替换到 html thead 中的“标题”
                    //{mDataProp:"js_Id", sClass:"text-c",  sTitle:"编号",sDefaultContent:""},
                    { mDataProp: "js_Id", sClass: "text-c", sTitle: "ID", sDefaultContent: "", sWidth: "10%" },
                    { mDataProp: "plcName", sClass: "text-c", sTitle: "PLC名称", sDefaultContent: "", sWidth: "8%" },
                    { mDataProp: "equipmentCode", sClass: "text-c", sTitle: "设备号", sDefaultContent: "", sWidth: "8%" },
                    { mDataProp: "dbCode", sClass: "text-c", sTitle: "DB编号", sDefaultContent: "", sWidth: "5%" },
                    { mDataProp: "dbStart", sClass: "text-c", sTitle: "DB读取起始位", sDefaultContent: "", sWidth: "5%" },
                    { mDataProp: "dbLength", sClass: "text-c", sTitle: "DB读取长度", sDefaultContent: "", sWidth: "5%" },
                    { mDataProp: "processModuleType", sClass: "text-c", sTitle: "报文处理模块类型", sDefaultContent: "", sWidth: "10%" },
                    { mDataProp: "processModuleName", sClass: "text-c", sTitle: "报文模块处理对象名称", sDefaultContent: "", sWidth: "10%" },
                    { mDataProp: "jobName", sClass: "text-c", sTitle: "任务名称", sDefaultContent: "", sWidth: "7%" },
                    { mDataProp: "plcConnectionIP", sClass: "text-c", sTitle: "PLC连接IP", sDefaultContent: "", sWidth: "5%" },
                    { mDataProp: "plcCpuTypeName", sClass: "text-c", sTitle: "CPU类型", sDefaultContent: "", sWidth: "5%" },
                    {
                        mDataProp: "isHeartbeat", sClass: "text-c", sTitle: "是否心跳", sDefaultContent: "", sWidth: "3%",
                        mRender: function (data, type, row) {
                            var html = "<span class=\"label label-success\">是</span>";
                            if (data == 0) {
                                html = "<span class=\"label label-danger\">否</span>";
                            }
                            return html;
                        }
                    },
                    {
                        mDataProp: "isEnable", sClass: "text-c", sTitle: "是否启用", sDefaultContent: "", sWidth: "3%",
                        mRender: function (data, type, row) {
                            var html = "<span class=\"label label-success\">是</span>";
                            if (data == 0) {
                                html = "<span class=\"label label-danger\">否</span>";
                            }
                            return html;
                        }
                    },
                    {
                        mDataProp: "js_Id", sClass: "text-c", sTitle: "操作", sWidth: "10%",
                        mRender: function (data, type, row) {
                            var html = "<a title=\"编辑\" href=\"javascript:;\" onclick=\"common_add('编辑PLC连接配置',\'/plcreaddb/plcreaddbinfoaddoredit/" + data + "','700','660')\" class=\"ml-5 btn btn-secondary-outline radius\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe6df; 编辑</i></a>";
                            html += "<a title=\"删除\" href=\"javascript:;\" onclick=\"DelPlcReadDBInfoAsync('" + data + "')\" class=\"ml-5  btn btn-danger-outline radius\" style=\"text-decoration:none\"><i class=\"Hui-iconfont\">&#xe609; 删除</i></a>";
                            return html;
                        }
                    }
                ],
                oLanguage: { //国际化配置
                    sProcessing: "正在获取数据，请稍后...",
                    sLengthMenu: "显示 _MENU_ 条",
                    sZeroRecords: "没有您要搜索的内容",
                    sInfo: "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",
                    sInfoEmpty: "记录数为0",
                    sInfoFiltered: "(全部记录数 _MAX_ 条)",
                    sInfoPostFix: "",
                    sSearch: "从当前数据中检索： ",
                    sUrl: "",
                    oPaginate: {
                        sFirst: "首页",
                        sPrevious: "上一页",
                        sNext: "下一页",
                        sLast: "尾页"
                    }
                }
            });
        }

        function DelPlcReadDBInfoAsync(id) {
            console.log(id);
            popupConfirm("确定删除该PLC读取DB配置吗？", 0, function () {
                var data = { 'id': id };
                SubmitFormForAjax("/plcreaddb/delplcreaddbinfo", data, function (data) {
                    if (data.result) {
                        popupAlert('删除成功！', 1, function () {
                            location.reload();//刷新页面
                        });
                    } else {
                        popupAlert('删除失败！', 1, function (data) {
                            layer.close(data);
                        });
                    }
                }, true);

            });
        }

        ///导入数据的模板下载
        function importDemo() {
            //模板数据
            const data = {
                header: ['PlcName', 'EquipmentCode', 'DbCode', 'DbCode2', 'DbStart', 'DbLength', 'ProcessModuleType', 'ProcessModuleName', 'JobID', 'PlcConnectionID', 'IsHeartbeat', 'IsEnable', 'ObjectType', 'PLCobjectName', 'WCSobjectName', 'objectLength', 'BytesIndex'],
                body: [
                    ['PLC名称', '设备号', 'plcDB', 'wcsDB', '偏移量', '读取长度', '报文处理模块类型', '报文模块处理对象名称', '作业名', '连接IP', '是否心跳', '是否启用', '写DB报文类', 'PLC报文解析类', 'WCCS报文解析类', '解析报文长度', '解析报文开始位置'],
                ]
            };

            const table = createTable(data);
            document.body.appendChild(table);
            tableToExcel(table);
        }


        //导入表格数据处理
        var wb;//读取完成的数据
        var rABS = false; //是否将文件读取为二进制字符串
        //EXCEL导入
        function importFun() {
            var f = $("#file")[0].files[0];
            var reader = new FileReader();
            reader.onload = function (e) {
                var data = e.target.result;
                if (rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary',
                        codepage: 936
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                //document.getElementById("divContent").innerHTML= JSON.stringify(
                //XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) );
                //var res=$("#divContent").html();
                var res = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
                appendTable(res);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        }

        //处理数据
        function appendTable(resStr) {
            console.log("导入数据：" + resStr);
            var res = JSON.parse(resStr);
            var htmlR = "";
            //console.log("导入数据：" + res);

            var fileDatas = [];
            for (var i = 1; i < res.length; i++) {
                fileDatas.push({
                    PlcName: res[i].PlcName,
                    EquipmentCode: res[i].EquipmentCode + "",
                    DbCode: res[i].DbCode,
                    DbCode2: res[i].DbCode2,
                    DbStart: res[i].DbStart,
                    DbLength: res[i].DbLength,
                    ProcessModuleType: res[i].ProcessModuleType,
                    ProcessModuleName: res[i].ProcessModuleName,
                    ProcessModuleNameWcs: res[i].ProcessModuleNameWcs,
                    JobID: res[i].JobID,
                    PlcConnectionID: res[i].PlcConnectionID,
                    IsHeartbeat: res[i].IsHeartbeat,
                    IsEnable: res[i].IsEnable,
                    ObjectType: res[i].ObjectType,
                    PLCobjectName: res[i].PLCobjectName,
                    WCSobjectName: res[i].WCSobjectName,
                    objectLength: res[i].objectLength,
                    BytesIndex: res[i].BytesIndex
                })
            }
            var requestJson = JSON.stringify(fileDatas);

            ////query(htmlR);
            //SubmitFormForAjax("/plcreaddb/AddPlcReadDBInfoByFiles", fileDatas, function (data) {
            //    if (data.result) {
            //        $("#btnSubmit").attr("disabled", false);
            //        popupAlert('提交成功', 1, function () { closePageLayer(true); });
            //    } else {
            //        $("#btnSubmit").attr("disabled", false);
            //        popupAlert(data.message, 2, function (data) { layer.close(data); });
            //    }
            //}, true);

            //$.ajax({
            //    url: "/plcreaddb/AddPlcReadDBInfoByFiles",
            //    data: JSON.stringify(fileDatas),
            //    type: "post",
            //    //application/x-www-formencoded、multipart/form-data、application/json
            //    contentType: "application/json; charset=utf-8",
            //    dataType: "json",
            //    success: function (res) {
            //        popupAlert('提交成功', 1, function () { closePageLayer(true); });
            //    },
            //    error: function (xhr, textStatus, errorThrown) {
            //        popupAlert(data.message, 2, function (data) { layer.close(data); });
            //    }
            //});
            $.ajax({
                url: '/plcreaddb/AddPlcReadDBInfoByFiles',
                type: 'post',//改成 get 方式后无法获取
                contentType: 'application/json',
                data: requestJson,
                success: function (data) {
                    alert(JSON.stringify(data))
                }
            });

            //追加完table后清空file
            $("#file").val('');
        }


        function createTable(data) {
            // 创建table元素
            const table = document.createElement('table');

            // 创建thead元素
            const thead = document.createElement('thead');
            const headRow = document.createElement('tr');
            //添加表头数据
            for (let i = 0; i < data.header.length; i++) {
                const th = document.createElement('th');
                th.innerHTML = data.header[i];
                headRow.appendChild(th);
            }
            thead.appendChild(headRow);

            // 创建tbody元素
            const tbody = document.createElement('tbody');
            // 添加表格数据
            for (let i = 0; i < data.body.length; i++) {
                const row = document.createElement('tr');
                for (let j = 0; j < data.body[i].length; j++) {
                    const cell = document.createElement('td');
                    cell.innerHTML = data.body[i][j];
                    row.appendChild(cell);
                }
                tbody.appendChild(row);
            }
            table.appendChild(thead);
            table.appendChild(tbody);

            return table;
        }

        function tableToExcel(table) {
            const workbook = XLSX.utils.book_new();

            // 将表格转化为sheet
            const sheet = XLSX.utils.table_to_sheet(table);
            XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');

            // 生成 Excel文件并自动下载
            const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
            function s2ab(s) {
                const buf = new ArrayBuffer(s.length);
                const view = new Uint8Array(buf);
                for (let i = 0; i < s.length; i++) {
                    view[i] = s.charCodeAt(i) & 0xFF;
                }
                return buf;
            }
            const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
            const filename = 'db模板.xlsx';
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

    </script>
}

